package com.atguigu.gmall.ums.service.impl;

import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.exception.MessageException;
import com.atguigu.gmall.mes.consts.ServiceConst;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.atguigu.gmall.ums.feign.GmallMesClient;
import com.atguigu.gmall.ums.mapper.UserMapper;
import com.atguigu.gmall.ums.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private GmallMesClient mesClient;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<UserEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<UserEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public Boolean checkData(String data, Integer type) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        switch (type) {
            case 1:
                queryWrapper.eq("username", data);
                break;
            case 2:
                queryWrapper.eq("phone", data);
                break;
            case 3:
                queryWrapper.eq("email", data);
                break;
            default:
                return null;
        }
        return this.count(queryWrapper) == 0;
    }

    @Override
    public void getCode(String phone) {
        mesClient.sendMessage(phone);
    }

    @Override
    public void register(UserEntity userEntity, String code) {
        //1、校验验证码：查询redis中的验证码 和 用户输入的验证码是否匹配
        String redisCode = redisTemplate.opsForValue().get(ServiceConst.CODE_TIMES_REGIST_PREFIX + userEntity.getPhone());
        if (StringUtils.isBlank(redisCode)) {
            throw new MessageException("验证码已失效 请重新获取");
        }
        if (!redisCode.equals(code)) {
            throw new MessageException("验证码输入错误");
        }
        //2、生成盐
        String salt = UUID.randomUUID().toString().substring(0, 6);
        userEntity.setSalt(salt);
        //3、加盐加密
        userEntity.setPassword(DigestUtils.md5Hex(userEntity.getPassword() + salt));
        //4、新增用户
        userEntity.setLevelId(1l);
        userEntity.setNickname(userEntity.getUsername());
        userEntity.setSourceType(1);
        userEntity.setIntegration(1000);
        userEntity.setGrowth(1000);
        userEntity.setStatus(1);
        userEntity.setCreateTime(new Date());
        this.save(userEntity);
        //5、删除redis中验证码
        redisTemplate.delete(ServiceConst.CODE_TIMES_REGIST_PREFIX + userEntity.getPhone());
    }

    @Override
    public UserEntity queryUser(String loginName, String password) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginName).or().eq("phone", loginName).or().eq("email", loginName);
        List<UserEntity> userEntities = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(userEntities)) {
            return null;
        }
        for (UserEntity userEntity : userEntities) {
            String pwd = userEntity.getPassword();
            String curPwd = DigestUtils.md5Hex(password + userEntity.getSalt());
            if (StringUtils.equals(pwd, curPwd)) {
                return userEntity;
            }
        }
        return null;
    }
}